﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;

public class LighteningMananger : MonoBehaviour
{
    public Vector3 startPos;
    public Vector3 endPos;
    public int steps;
    public float duration;

    private LineRenderer _lineRenderer;
    private int stepNow = 0;

    private void Awake()
    {
        _lineRenderer = GetComponent<LineRenderer>();
    }

    void OnGUI()
    {
        if (GUILayout.Button("Start"))
        {
            NextStep();
            Reset();
        }
    }

    void NextStep()
    {
        _lineRenderer.SetVertexCount(stepNow+1);
        float pcg = (float) (stepNow + 1) / (float) steps;
        Vector3 pos = Vector3.Lerp(startPos,endPos,pcg) + new Vector3(Random.Range(-.5f,.5f),Random.Range(-.1f,.1f),0);
        _lineRenderer.SetPosition(stepNow,pos);

        if (stepNow < steps)
        {
            stepNow++;
            Invoke("NextStep",duration/(float)steps);
        }
    }


    private void Reset()
    {
        CancelInvoke();
        stepNow = 0;
        _lineRenderer.SetVertexCount(0);
    }
}
